package com.ruoyi.electronicFence.service.Impl;

import java.time.*;
import java.util.*;

import com.ruoyi.common.GenericMethods;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.electronicFence.domain.*;
import com.ruoyi.electronicFence.mapper.TEfAlarmPersonMapper;
import com.ruoyi.electronicFence.mapper.TEfEquipmentDeviceMapper;
import com.ruoyi.electronicFence.mapper.TEquipmentMonitorDeviceMapper;
import com.ruoyi.electronicFence.service.ITDeviceStatusService;
import com.ruoyi.electronicFence.service.ITEfEquipmentDeviceService;

import com.ruoyi.electronicFence.service.ITEfHistoryEquipmentStatusService;
import kong.unirest.json.JSONException;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.electronicFence.mapper.TEfAlarmMapper;
import com.ruoyi.electronicFence.service.ITEfAlarmService;

/**
 * 电子围栏报警信息Service业务层处理
 *
 * @author sxygsj
 * @date 2024-05-20
 */
@Service
public class TEfAlarmServiceImpl implements ITEfAlarmService
{


    private final TEfAlarmMapper tEfAlarmMapper;
    private final TEfAlarmPersonMapper tEfAlarmPersonMapper;
    private final TEfEquipmentDeviceMapper tEfEquipmentDeviceMapper;
    private final ITDeviceStatusService tDeviceStatusService;
    private final ITEfEquipmentDeviceService tEfEquipmentDeviceService;
    private final TEquipmentMonitorDeviceMapper tEquipmentMonitorDeviceMapper;
    private final ITEfHistoryEquipmentStatusService iTEfHistoryEquipmentStatusService;

    @Value("${system.stacked_seconds}")
    Integer STACKED_SECONDS;



//
    @Autowired
    public TEfAlarmServiceImpl(TEfAlarmMapper tEfAlarmMapper, TEfAlarmPersonMapper tEfAlarmPersonMapper, TEfEquipmentDeviceMapper tEfEquipmentDeviceMapper,
                               ITDeviceStatusService tDeviceStatusService, ITEfEquipmentDeviceService tEfEquipmentDeviceService,
                               TEquipmentMonitorDeviceMapper tEquipmentMonitorDeviceMapper,ITEfHistoryEquipmentStatusService iTEfHistoryEquipmentStatusService) {
        this.tEfAlarmMapper = tEfAlarmMapper;
        this.tEfAlarmPersonMapper = tEfAlarmPersonMapper;
        this.tEfEquipmentDeviceMapper = tEfEquipmentDeviceMapper;
        this.tDeviceStatusService = tDeviceStatusService;
        this.tEfEquipmentDeviceService = tEfEquipmentDeviceService;
        this.tEquipmentMonitorDeviceMapper = tEquipmentMonitorDeviceMapper;
        this.iTEfHistoryEquipmentStatusService = iTEfHistoryEquipmentStatusService;


    }



    /**
     * 查询电子围栏报警信息
     *
     * @param id 电子围栏报警信息主键
     * @return 电子围栏报警信息
     */
    @Override
    public TEfAlarm selectTEfAlarmById(Long id)
    {
        return tEfAlarmMapper.selectTEfAlarmById(id);
    }

    /**
     * 查询电子围栏报警信息列表
     *
     * @param tEfAlarm 电子围栏报警信息
     * @return 电子围栏报警信息
     */
    @Override
    public List<TEfAlarm> selectTEfAlarmList(TEfAlarm tEfAlarm)
    {
        return tEfAlarmMapper.selectTEfAlarmList(tEfAlarm);
    }

    /**
     * 查询电子围栏报警信息列表
     *
     * @param tEfAlarm 电子围栏报警信息
     * @return 电子围栏报警信息
     */
    @Override
    public List<TEfAlarm> selectTEfAlarmList2(TEfAlarm tEfAlarm)
    {

        List<TEfAlarm> TEfAlarms = tEfAlarmMapper.selectTEfAlarmList2(tEfAlarm);
        for (TEfAlarm  Alarm :TEfAlarms){

            String pictureUrls = Alarm.getPictureUrls();
            if (pictureUrls != null) {
                try {
                    JSONArray jsonArray = new JSONArray(pictureUrls);
                    List<String> urlList = new ArrayList<>(jsonArray.length()); // 预分配容量

                    for (int i = 0; i < jsonArray.length(); i++) {
                        Object item = jsonArray.get(i);
                        if (item instanceof String) { // 只添加String类型的项目
                            urlList.add((String) item);
                        }
                    }

                    Alarm.setPictureUrlList(urlList);

                } catch (JSONException e) {
                    // 处理 JSON 解析错误
                    e.printStackTrace();
                    // 或者你可以选择记录日志、跳过当前项等操作
                }
            }



        }

        //遍历取出 personId 集合
        List<TEfAlarmPerson> tEfAlarmPeoples = tEfAlarmPersonMapper.selectTEfAlarmPersonListByPersonIds(TEfAlarms);
        //遍历两个列表 当TEfAlarms中的 personSubId 和  tEfAlarmPeoples 的personId 相同的记录 然后 在将tEfAlarmPeoples中 alarmType 等于0记录插入
        //当TEfAlarms中的 List<TEfAlarmPerson> tEfAlarmPerson0 数组中 帮我实现
        List<TEfAlarmPerson> tEfAlarmPerson = new ArrayList<>();
        List<TEfAlarmPerson> tEfAlarmPerson0 = new ArrayList<>();
        List<TEfAlarmPerson> tEfAlarmPerson1 = new ArrayList<>();


        // 遍历 TEfAlarms 和 tEfAlarmPeoples，根据条件筛选符合要求的记录
//        for (TEfAlarm alarm : TEfAlarms) {
//            for (TEfAlarmPerson person : tEfAlarmPeoples) {
//                if (alarm.getPersonSubId()!=null){
//                    tEfAlarmPerson.add(person);
//                    // 判断条件：TEfAlarms 中的 personSubId 和 tEfAlarmPeoples 中的 personId 相同，并且 alarmType 等于 0
//                    if (alarm.getPersonSubId().equals(person.getPersonId()) && person.getAlarmType().equals("0")) {
//                        tEfAlarmPerson0.add(person);
//                    }
//                    // 判断条件：TEfAlarms 中的 personSubId 和 tEfAlarmPeoples 中的 personId 相同，并且 alarmType 等于 0
//                    if (alarm.getPersonSubId().equals(person.getPersonId()) && person.getAlarmType().equals("1")) {
//                        tEfAlarmPerson1.add(person);
//                    }
//                    alarm.setTEfAlarmPerson(tEfAlarmPerson);
//                    alarm.setTEfAlarmPerson0(tEfAlarmPerson0);
//                    alarm.setTEfAlarmPerson1(tEfAlarmPerson1);
//                }
//
//            }
//
//
//        }

        return TEfAlarms;
    }

    @Override
    public List<TEfAlarm> selectDetailsList(TEfAlarm tEfAlarm) {
        List<TEfAlarm> tEfAlarms = tEfAlarmMapper.selectDetailsList(tEfAlarm);
        List<TEfAlarm> tEfAlarmsType0 = tEfAlarmMapper.selectDetailsListType0(tEfAlarm);
        List<TEfAlarm> tEfAlarmsType1 = tEfAlarmMapper.selectDetailsListType1(tEfAlarm);
        // 创建一个Map来保存tEfAlarmsType1中所有TEfAlarm的personId与其对应的TEfAlarmPerson列表
        Map<String, List<TEfAlarmPerson>> personIdToPersonsMap0 = new HashMap<>();
        Map<String, List<TEfAlarmPerson>> personIdToPersonsMap1 = new HashMap<>();

        // 遍历tEfAlarmsType1，准备数据
        for (TEfAlarm alarm0 : tEfAlarmsType0) {
            if (alarm0.getTEfAlarmPerson() != null && !alarm0.getTEfAlarmPerson().isEmpty()) {
                for (TEfAlarmPerson person : alarm0.getTEfAlarmPerson()) {
                    personIdToPersonsMap0.computeIfAbsent(person.getPersonId(), k -> new ArrayList<>()).add(person);
                }
            }
        }

        // 遍历tEfAlarmsType1，准备数据
        for (TEfAlarm alarm1 : tEfAlarmsType1) {
            if (alarm1.getTEfAlarmPerson() != null && !alarm1.getTEfAlarmPerson().isEmpty()) {
                for (TEfAlarmPerson person : alarm1.getTEfAlarmPerson()) {
                    personIdToPersonsMap1.computeIfAbsent(person.getPersonId(), k -> new ArrayList<>()).add(person);
                }
            }
        }

    // 遍历tEfAlarmsType0，查找匹配并添加TEfAlarmPerson
        for (TEfAlarm alarm : tEfAlarms) {
            String personId = alarm.getPersonSubId(); // 假设这里有一个getPersonId方法来获取personId
//            System.out.println(personId);
            List<TEfAlarmPerson> persons0 = personIdToPersonsMap0.get(personId);
            List<TEfAlarmPerson> persons1 = personIdToPersonsMap1.get(personId);

            if (persons0 != null) {
                // 如果找到匹配的personId，则将对应的TEfAlarmPerson列表添加到alarm0中
                alarm.setTEfAlarmPerson0(persons0); // 假设这里有一个setTEfAlarmPerson方法来设置列表
            }
            if (persons1 != null) {
                // 如果找到匹配的personId，则将对应的TEfAlarmPerson列表添加到alarm0中
                alarm.setTEfAlarmPerson1(persons1); // 假设这里有一个setTEfAlarmPerson方法来设置列表
            }
        }
        return tEfAlarms;

    }

    @Override
    public int selectDetailsListTotal(TEfAlarm tEfAlarm) {
        int total = tEfAlarmMapper.selectDetailsListTotal(tEfAlarm);
        return total;
    }


    /**
     * 新增电子围栏报警信息
     *
     * @param tEfAlarm 电子围栏报警信息
     * @return 结果
     */
    @Override
    public int insertTEfAlarm(TEfAlarm tEfAlarm)
    {
        return tEfAlarmMapper.insertTEfAlarm(tEfAlarm);
    }

    /**
     * 修改电子围栏报警信息
     *
     * @param tEfAlarm 电子围栏报警信息
     * @return 结果
     */
    @Override
    public int updateTEfAlarm(TEfAlarm tEfAlarm)
    {
        return tEfAlarmMapper.updateTEfAlarm(tEfAlarm);
    }

    /**
     * 批量删除电子围栏报警信息
     *
     * @param ids 需要删除的电子围栏报警信息主键
     * @return 结果
     */
    @Override
    public int deleteTEfAlarmByIds(Long[] ids)
    {
        return tEfAlarmMapper.deleteTEfAlarmByIds(ids);
    }

    /**
     * 删除电子围栏报警信息信息
     *
     * @param id 电子围栏报警信息主键
     * @return 结果
     */
    @Override
    public int deleteTEfAlarmById(Long id)
    {
        return tEfAlarmMapper.deleteTEfAlarmById(id);
    }

    /**
     * 报警数据入库
     *
     *
     * @return 结果
     */
    @Override
    public int InboundDataOftAlarm(ReceiveEFData receiveEFData)
    {
        /*
        解析数据
         */
        TEfAlarm tEfAlarm = new TEfAlarm();
        // 告警时间
        tEfAlarm.setAlarmTime(receiveEFData.getAlarmTime());
        //IP 转ID
        String MonitorDeviceId = GenericMethods.convertIpToNumeric(receiveEFData.getControllerIP());
        // 告警值
        //tEfAlarm.setAlarmValue(receiveEFData.getAlarmValue());
        // 告警监测设备id
        tEfAlarm.setMonitorDeviceId(MonitorDeviceId);
        String controllerStatus = receiveEFData.getControllerStatus();
        if (controllerStatus.equals("0")){
            controllerStatus="正常";
        }
        if (controllerStatus.equals("1")){
            controllerStatus="预警";
        }
        if (controllerStatus.equals("2")){
            controllerStatus="停机";
        }
        if (controllerStatus.equals("3")){
            controllerStatus="离线";
        }
        //更新监测设备 、以及所在的场所状态、新增历史状态修改
        TEfEquipmentDevice tEfEquipmentDevice = updateDeviceAndEquipmentV2(MonitorDeviceId, controllerStatus);
        String deviceName = tEfEquipmentDevice.getDeviceName();
        String equipmentName = tEfEquipmentDevice.getEquipmentName();
        tEfAlarm.setAlarmDevice(equipmentName);
        tEfAlarm.setMonitorDeviceName(deviceName);

        if (StringUtils.isNotEmpty(receiveEFData.getControllerStatus()) ){
            if ("0".equals(receiveEFData.getControllerStatus())){
                // TODO: 需要将设备状态也同时更新
                return 0;
            }
            else if("1".equals(receiveEFData.getControllerStatus())){
                tEfAlarm.setAlarmType("预警");

            }
            else if("2".equals(receiveEFData.getControllerStatus())){
                tEfAlarm.setAlarmType("停机");

            }
        }

        // 告警监测设备名称
//        tEfAlarm.setMonitorDeviceName((receiveEFData.getMonitorDeviceName()));
        // 告警监测设备类型
        if (StringUtils.isNotEmpty(receiveEFData.getAlarmType()) ){
            String[] alarmType = receiveEFData.getAlarmType();
            // 使用 Arrays.toString 方法将数组转换为字符串
            String alarmTypeStr = Arrays.toString(alarmType);
            tEfAlarm.setMonitorDeviceType(alarmTypeStr);
        }
        if (StringUtils.isNotEmpty(receiveEFData.getPictureUrl()) ){
            tEfAlarm.setPictureUrl(receiveEFData.getPictureUrl());
        }

        // 告警监测设备类型
        List<Map<String,Object>> alarmCardIdList = receiveEFData.getPersonCardInfoMap().get("alarmList");
        List<Map<String,Object>> shutdownCardIdList = receiveEFData.getPersonCardInfoMap().get("shutdownList");
//        tEfAlarm.setAlarmCardIdList();
        UUID PersonId = UUID.randomUUID();
        tEfAlarm.setPersonSubId(PersonId.toString());
        if (tEfEquipmentDevice!=null){
            tEfAlarm.setAlarmArea(tEfEquipmentDevice.getAreaName());
            tEfAlarm.setPlaceType(tEfEquipmentDevice.getAreaType());
//            tEfAlarm.setAlarmDevice(tEfEquipmentDevice.getDeviceName());
        }
        tEfAlarm.setStatusStartDatetime(LocalDateTime.now());

        //更新设备状态
        //
        int i = tEfAlarmMapper.insertTEfAlarm(tEfAlarm);
        if(alarmCardIdList.size()>0){
            for (Map<String,Object> eFPersonnel :alarmCardIdList){
                TEfAlarmPerson tEfAlarmPerson = new TEfAlarmPerson();
                tEfAlarmPerson.setPersonId(PersonId.toString());
                tEfAlarmPerson.setAlarmType("0");
                tEfAlarmPerson.setCardId((String) eFPersonnel.get("cardId"));
//            tEfAlarmPerson.setCardReaderId(eFPersonnel.getCardReaderId());
//                int distance = ((Integer) eFPersonnel.get("distance")).intValue();
                String distanceStr = eFPersonnel.get("distance").toString();
                tEfAlarmPerson.setDistance(Double.parseDouble(distanceStr));
                tEfAlarmPersonMapper.insertTEfAlarmPerson(tEfAlarmPerson);
            }
        }

        if (shutdownCardIdList.size()>0){
            for (Map<String,Object>  eFPersonnel :shutdownCardIdList){
                TEfAlarmPerson tEfAlarmPerson = new TEfAlarmPerson();
                tEfAlarmPerson.setPersonId(PersonId.toString());
                tEfAlarmPerson.setAlarmType("1");
                tEfAlarmPerson.setCardId((String) eFPersonnel.get("cardId"));
                String distanceStr = eFPersonnel.get("distance").toString();
                tEfAlarmPerson.setDistance(Double.parseDouble(distanceStr));
//                tEfAlarmPerson.setDistance(eFPersonnel.getDistance());
                tEfAlarmPersonMapper.insertTEfAlarmPerson(tEfAlarmPerson);
            }
        }

        return i;
    }

    @Override
    public int InboundDataOftAlarmV2(ReceiveEFData receiveEFData)
    {
        /*
        解析数据
         */
        TEfAlarm tEfAlarm = new TEfAlarm();
        //IP 转ID
        String MonitorDeviceId = GenericMethods.convertIpToNumeric(receiveEFData.getControllerIP());
        tEfAlarm.setApeName(receiveEFData.getApeName());
        tEfAlarm.setApeId(receiveEFData.getApeId());

        // 告警值
        //tEfAlarm.setAlarmValue(receiveEFData.getAlarmValue());
        // 告警监测设备id
        tEfAlarm.setMonitorDeviceId(MonitorDeviceId);
        String controllerStatus = receiveEFData.getControllerStatus();

        switch (controllerStatus) {
            case "0":
                controllerStatus = "正常";
                break;
            case "1":
                controllerStatus = "预警";
                break;
            case "2":
                controllerStatus = "停机";
                break;
            case "3":
                controllerStatus = "离线";
                break;
        }


        //更新监测设备 、以及所在的场所状态、新增历史状态修改
        TEfEquipmentDevice tEfEquipmentDevice = updateDeviceAndEquipmentV2(MonitorDeviceId, controllerStatus);
        String deviceName = tEfEquipmentDevice.getDeviceName();
        String equipmentName = tEfEquipmentDevice.getEquipmentName();
        tEfAlarm.setAlarmDevice(equipmentName);
        tEfAlarm.setMonitorDeviceName(deviceName);
        // 设置报警类型
        if (StringUtils.isNotEmpty(receiveEFData.getControllerStatus())) {
            switch (receiveEFData.getControllerStatus()) {
                case "0":
                    // 正常状态，不做处理
                    break;
                case "1":
                    tEfAlarm.setAlarmType("预警");
                    break;
                case "2":
                    tEfAlarm.setAlarmType("停机");
                    break;
            }
        }
        int rows = 0;

        // 设置告警监测设备类型和图片URL
        if ("1".equals(receiveEFData.getControllerStatus()) || "2".equals(receiveEFData.getControllerStatus())) {
            setAlarmDetails(tEfAlarm, receiveEFData);

            // 设置人员子ID
            tEfAlarm.setPersonSubId(UUID.randomUUID().toString());

            // 设置区域和场所类型
            if (tEfEquipmentDevice != null) {
                tEfAlarm.setAlarmArea(tEfEquipmentDevice.getAreaName());
                tEfAlarm.setPlaceType(tEfEquipmentDevice.getAreaType());
            }

            // 获取上一条数据
            TEfAlarm tEfAlarmLast = tEfAlarmMapper.selectTEfAlarmLast(MonitorDeviceId);
            LocalDateTime now = LocalDateTime.now().withNano(0);
            tEfAlarm.setAlarmTime(now);

            if (tEfAlarmLast == null) {
                // 没有上一条数据，处理首条报警记录
                handleFirstAlarmRecord(tEfAlarm, now);
                rows = tEfAlarmMapper.insertTEfAlarm(tEfAlarm);
            } else {
                // 处理有上一条数据的情况
                handleExistingAlarmRecord(tEfAlarm, tEfAlarmLast, now);
            }
        }

        return rows;
    }

    /**
     * 设置告警详情信息。
     *
     * @param tEfAlarm 告警对象
     * @param receiveEFData 接收到的数据对象
     */
    private void setAlarmDetails(TEfAlarm tEfAlarm, ReceiveEFData receiveEFData) {
        // 设置告警监测设备类型
        if (StringUtils.isNotEmpty(receiveEFData.getAlarmType())) {
            String[] alarmType = receiveEFData.getAlarmType();
            tEfAlarm.setMonitorDeviceType(Arrays.toString(alarmType));
        }

        // 设置告警图片URL
        if (StringUtils.isNotEmpty(receiveEFData.getPictureUrl())) {
            tEfAlarm.setPictureUrl(receiveEFData.getPictureUrl());
        }

        // 处理人员卡信息
        if (receiveEFData.getPersonCardInfoMap() != null) {
            List<Map<String, Object>> alarmCardIdList = receiveEFData.getPersonCardInfoMap().get("alarmList");
            List<Map<String, Object>> shutdownCardIdList = receiveEFData.getPersonCardInfoMap().get("shutdownList");

            // 可以在这里处理 alarmCardIdList 和 shutdownCardIdList
            // 例如：
            // tEfAlarm.setAlarmCardIdList(alarmCardIdList);
            // tEfAlarm.setShutdownCardIdList(shutdownCardIdList);
        }
    }

    /**
     * 处理第一个报警记录的方法。
     *
     * @param tEfAlarm 报警对象，包含报警的相关信息。
     * @param now 当前的时间点，用于设置报警的状态开始时间和结束时间。
     */
    private void handleFirstAlarmRecord(TEfAlarm tEfAlarm, LocalDateTime now) {
        // 设置报警的状态开始时间为当前时间
        tEfAlarm.setStatusStartDatetime(now);

        // 设置报警的状态结束时间为当前时间加上1秒，表示报警持续了1秒
        tEfAlarm.setStatusEndDatetime(now.plusSeconds(1));

        // 设置报警的持续时间为1秒
        tEfAlarm.setDurationSeconds(1);

        // 将持续时间转换为字符串格式，并设置到报警对象中
        tEfAlarm.setDurationSecondsStr(GenericMethods.formatDuration(1));

        // 如果存在图片URL，则将其设置到 pictureUrls 属性中
        if (tEfAlarm.getPictureUrl() != null) {
            // 将单一的图片URL设置到 pictureUrls 属性中
            // 注意：这里假设 pictureUrls 应该是一个 JSON 数组，因此需要将单一的 URL 转换为数组格式
            String pictureUrlJsonArray = "[\"" + tEfAlarm.getPictureUrl() + "\"]";
            tEfAlarm.setPictureUrls(pictureUrlJsonArray);
        }
    }

    private void handleExistingAlarmRecord(TEfAlarm tEfAlarm, TEfAlarm tEfAlarmLast, LocalDateTime now) {
        String alarmTypeLast = tEfAlarmLast.getAlarmType();
        String pictureUrlLast = tEfAlarmLast.getPictureUrl();

        Duration durationSinceStart = Duration.between(tEfAlarmLast.getStatusEndDatetime(), now);
        long secondsElapsed = durationSinceStart.getSeconds();
        boolean isAlarmTypeConsistent = alarmTypeLast != null && alarmTypeLast.equals(tEfAlarm.getAlarmType());
        boolean isRecentAlarm = secondsElapsed < STACKED_SECONDS;
        boolean isPictureUrlSame = StringUtils.isNotEmpty(tEfAlarm.getPictureUrl()) &&
                pictureUrlLast != null && pictureUrlLast.equals(tEfAlarm.getPictureUrl());

        //报警类型一致 、且报警间隔小于 xx秒 进行报警记录合并
        if (isAlarmTypeConsistent && isRecentAlarm) {
            updateExistingAlarmRecord(tEfAlarm, tEfAlarmLast, now, isPictureUrlSame,secondsElapsed);

        } else {
            //新增首条
            handleFirstAlarmRecord(tEfAlarm,now);
            tEfAlarmMapper.insertTEfAlarm(tEfAlarm);

        }

    }

    private void updateExistingAlarmRecord(TEfAlarm tEfAlarm, TEfAlarm tEfAlarmLast, LocalDateTime now,
                                           boolean isPictureUrlSame,long secondsElapsed) {
        // 创建一个新的 TEfAlarm 对象，用于更新现有的报警记录
        TEfAlarm tEfAlarmUpdate = new TEfAlarm();
        tEfAlarmUpdate.setPictureUrl(tEfAlarm.getPictureUrl()); // 设置新的图片URL
        Integer durationSeconds = tEfAlarmLast.getDurationSeconds();
        // 检查 tEfAlarmLast 的 pictureUrls 是否不为空
        if (tEfAlarmLast.getPictureUrls() != null) {
            // 将 JSON 数组字符串转换为 JSONArray 对象
            JSONArray jsonArray = new JSONArray(tEfAlarmLast.getPictureUrls());
            // 创建一个列表来存储图片 URL
            List<String> urlList = new ArrayList<>();

            // 遍历 JSONArray 并将每个 URL 添加到列表中
            for (int k = 0; k < jsonArray.length(); k++) {
                urlList.add(jsonArray.getString(k));
            }

            // 如果新的图片 URL 不同于最后一个记录的图片 URL
            if (!isPictureUrlSame) {
                if (tEfAlarm.getPictureUrl()!=null){
                    // 如果 URL 列表的大小超过 99 个
                    if (urlList.size() > 99) {
                        // 移除第一个 URL
                        urlList.remove(0);
                        // 添加新的图片 URL
                        urlList.add(tEfAlarm.getPictureUrl());
                    } else {
                        // 直接添加新的图片 URL
                        urlList.add(tEfAlarm.getPictureUrl());
                    }

                    // 将更新后的 URL 列表转换回 JSON 字符串并设置到 tEfAlarmUpdate 对象中
                    tEfAlarmUpdate.setPictureUrls(new JSONArray(urlList).toString());
                }

            }


        }
        tEfAlarmUpdate.setStatusEndDatetime(now);
        if (secondsElapsed == 0){
            secondsElapsed=1L;
            tEfAlarmUpdate.setStatusEndDatetime(now.plusSeconds(1));
        }
        // 设置报警记录的结束时间 如果两者一致 则给截止时间+1秒

        tEfAlarmUpdate.setDurationSeconds((int) secondsElapsed+durationSeconds); // 设置持续时间的秒数
        tEfAlarmUpdate.setDurationSecondsStr(GenericMethods.formatDuration( (int) secondsElapsed+durationSeconds)); // 格式化持续时间并设置

        // 设置要更新的记录的 ID
        tEfAlarmUpdate.setId(tEfAlarmLast.getId());

        // 调用 Mapper 方法更新数据库中的报警记录
        tEfAlarmMapper.updateTEfAlarm(tEfAlarmUpdate);
    }

//    private void insertNewAlarmRecord(TEfAlarm tEfAlarm, LocalDateTime now) {
//        tEfAlarm.setStatusStartDatetime(now);
//        tEfAlarm.setStatusEndDatetime(now.plusSeconds(1));
//        tEfAlarm.setDurationSeconds(1);
//        tEfAlarm.setDurationSecondsStr(GenericMethods.formatDuration(1));
//        tEfAlarmMapper.insertTEfAlarm(tEfAlarm);
//    }

//
    @Override
    public List<TEfAlarm> completionAlarmInfo(List<TEfAlarm> tEfAlarms) {
        return null;
    }
    /*
    接收报警数据同时 更新控制器状态、和场所状态的持续时间、历史记录存储
     */
    public TEfEquipmentDevice updateDeviceAndEquipment(String MonitorDeviceId,String controllerStatus)
    {
        //获取场景信息
        TEfEquipmentDevice tEfEquipmentDevice1 = new TEfEquipmentDevice();
        tEfEquipmentDevice1.setControllerId(MonitorDeviceId);
        TEquipmentMonitorDevice tEquipmentMonitorDevice = new TEquipmentMonitorDevice();
        tEquipmentMonitorDevice.setMonitorDeviceId(MonitorDeviceId);
        List<TEquipmentMonitorDevice> tEquipmentMonitorDevices = tEquipmentMonitorDeviceMapper.selectTEquipmentMonitorDeviceList(tEquipmentMonitorDevice);
        String equipmentId = tEquipmentMonitorDevices.get(0).getEquipmentId();
        tEfEquipmentDevice1.setDeviceId(equipmentId);
        //获取
//        List<TEfEquipmentDeviceVo> tEfEquipmentDeviceVos = tEfEquipmentDeviceService.selectTEfEquipmentDeviceDetailsListV2(tEfEquipmentDevice1);
//        TEfEquipmentDeviceVo tEfEquipmentDeviceVo = tEfEquipmentDeviceVos.get(0);
        //获取场所信息
        TEfEquipmentDevice tEfEquipmentDevice = tEfEquipmentDeviceService.selectTEfEquipmentDeviceByDeviceId(equipmentId);
        TDeviceStatus deviceStatus = new TDeviceStatus();
        deviceStatus.setDeviceId(MonitorDeviceId);
        //获取监测设备信息
        List<TDeviceStatus> tDeviceStatuses = tDeviceStatusService.selectTDeviceStatusList(deviceStatus);
        String deviceName = tDeviceStatuses.get(0).getDeviceName();
        tEfEquipmentDevice.setDeviceName(deviceName);
        if (tEfEquipmentDevice!=null){
            TEfEquipmentDevice tEfEquipmentDeviceUpdate = new TEfEquipmentDevice();
            tEfEquipmentDeviceUpdate.setId(tEfEquipmentDevice.getId());

            LocalDateTime dataTime= LocalDateTime.now().withNano(0);
            LocalDateTime now = LocalDateTime.now().withNano(0);
                if (tEfEquipmentDevice.getDataTime()!=null) {
                    dataTime =tEfEquipmentDevice.getDataTime();
                }
                // 计算两个LocalDateTime之间的Duration
                Duration duration = Duration.between(dataTime, now);
            long seconds = duration.getSeconds();
            // 如果有纳秒部分，则向上取整
            if (duration.getNano() > 0) {
                seconds++;
            }
                // 获取秒差
                Integer secondsBetween =(int)seconds;
                Integer durationSeconds = tEfEquipmentDevice.getDurationSeconds();
                Integer oldDurationSeconds=durationSeconds;
                durationSeconds=durationSeconds+secondsBetween;
                String alarmType="";
                if (tEfEquipmentDevice.getAlarmType()!=null){
                     alarmType = tEfEquipmentDevice.getAlarmType();
                }else {
                    tEfEquipmentDeviceUpdate.setAlarmType("0");
                }

                //进行持续时间的判断
                tEfEquipmentDeviceUpdate.setDataTime(now);
                if (controllerStatus.equals(alarmType)){
                    tEfEquipmentDeviceUpdate.setDurationSeconds(durationSeconds);
                    tEfEquipmentDeviceUpdate.setAlarmType(controllerStatus);
                    tEfEquipmentDeviceService.updateTEfEquipmentDevice(tEfEquipmentDeviceUpdate);

                }else {
                    TEfHistoryEquipmentStatus tEfHistoryEquipmentStatus = new TEfHistoryEquipmentStatus();
                    tEfHistoryEquipmentStatus.setAreaName(tEfEquipmentDevice.getAreaName());
                    tEfHistoryEquipmentStatus.setEquipmentName(tEfEquipmentDevice.getEquipmentName());
                    tEfHistoryEquipmentStatus.setDeviceId(tEfEquipmentDevice.getDeviceId());
                    tEfHistoryEquipmentStatus.setAlarmType(controllerStatus);
                    tEfHistoryEquipmentStatus.setDurationSeconds(oldDurationSeconds);
                    String durationSecondsStr = GenericMethods.formatDuration(oldDurationSeconds);
                    tEfHistoryEquipmentStatus.setDurationSecondsStr(durationSecondsStr);
                    tEfHistoryEquipmentStatus.setDataTime(dataTime);
                    if (dataTime!=null){
                        // 将LocalDateTime转换为ZonedDateTime
                        ZonedDateTime zonedDateTime = dataTime.atZone(ZoneOffset.UTC);
                        // 从ZonedDateTime中提取Instant，并减去秒数
                        Instant instant = zonedDateTime.toInstant().minusSeconds(oldDurationSeconds);
                        // 将结果转换回LocalDateTime
                        LocalDateTime resultDateTime = instant.atZone(ZoneOffset.UTC).toLocalDateTime();
                        tEfHistoryEquipmentStatus.setStatusStartDatetime(resultDateTime);
                    }

                    int i = iTEfHistoryEquipmentStatusService.insertTEfHistoryEquipmentStatus(tEfHistoryEquipmentStatus);
                    tEfEquipmentDeviceUpdate.setDurationSeconds(1);
                    tEfEquipmentDeviceUpdate.setAlarmType(controllerStatus);
                    tEfEquipmentDeviceService.updateTEfEquipmentDevice(tEfEquipmentDeviceUpdate);
                }


        }
        return tEfEquipmentDevice;
    }


    public TEfEquipmentDevice updateDeviceAndEquipmentV2(String MonitorDeviceId,String controllerStatus)
    {
        //获取监测设备和场所的关联信息
        TEquipmentMonitorDevice tEquipmentMonitorDevice = new TEquipmentMonitorDevice();
        tEquipmentMonitorDevice.setMonitorDeviceId(MonitorDeviceId);
        List<TEquipmentMonitorDevice> tEquipmentMonitorDevices = tEquipmentMonitorDeviceMapper.selectTEquipmentMonitorDeviceList(tEquipmentMonitorDevice);
        String equipmentId = tEquipmentMonitorDevices.get(0).getEquipmentId();//获取对应的场所ID

        //获取监测设备最新的监测记录
        TEfHistoryEquipmentStatus HistoryRequest = new TEfHistoryEquipmentStatus();
        HistoryRequest.setDeviceId(equipmentId);
        TEfHistoryEquipmentStatus tEfHistoryEquipmentStatusLast = iTEfHistoryEquipmentStatusService.selectTEfHistoryEquipmentStatusLast(HistoryRequest);
        //获取场所信息
        TEfEquipmentDevice tEfEquipmentDevice = tEfEquipmentDeviceService.selectTEfEquipmentDeviceByDeviceId(equipmentId);
        //获取监测设备信息
        TDeviceStatus deviceStatus = new TDeviceStatus();
        deviceStatus.setDeviceId(MonitorDeviceId);
        List<TDeviceStatus> tDeviceStatuses = tDeviceStatusService.selectTDeviceStatusList(deviceStatus);
        String deviceName = tDeviceStatuses.get(0).getDeviceName();
        tEfEquipmentDevice.setDeviceName(deviceName);

        LocalDateTime now = LocalDateTime.now().withNano(0);
        if (tEfEquipmentDevice!=null) { //健壮性考虑 没有设置安装位置的情况
            TEfHistoryEquipmentStatus tEfHistoryEquipmentStatus = new TEfHistoryEquipmentStatus();
            tEfHistoryEquipmentStatus.setAreaId(tEfEquipmentDevice.getAreaId());
            tEfHistoryEquipmentStatus.setAreaType(tEfEquipmentDevice.getAreaType());
            tEfHistoryEquipmentStatus.setAreaName(tEfEquipmentDevice.getAreaName());
            tEfHistoryEquipmentStatus.setEquipmentName(tEfEquipmentDevice.getEquipmentName());
            //先判断历史记录是否为首条记录 首条记录直接新增
            if(tEfHistoryEquipmentStatusLast==null){
                tEfHistoryEquipmentStatus.setDeviceId(tEfEquipmentDevice.getDeviceId());
                tEfHistoryEquipmentStatus.setEquipmentStatus(controllerStatus);
                tEfHistoryEquipmentStatus.setDataTime(now);
                tEfHistoryEquipmentStatus.setStatusStartDatetime(now);
                tEfHistoryEquipmentStatus.setStatusEndDatetime(now.plusSeconds(1));
                tEfHistoryEquipmentStatus.setDurationSeconds(1);
                String durationSecondsStr = GenericMethods.formatDuration(1);
                tEfHistoryEquipmentStatus.setDurationSecondsStr(durationSecondsStr);
                iTEfHistoryEquipmentStatusService.insertTEfHistoryEquipmentStatus(tEfHistoryEquipmentStatus);
            }else {
                //判断状态变更情况 未发生变更则更新记录 发生变时 修改上一条记录 同时新增记录
                TEfHistoryEquipmentStatus update = new TEfHistoryEquipmentStatus();
                if (controllerStatus.equals(tEfHistoryEquipmentStatusLast.getEquipmentStatus())){
                    LocalDateTime statusStartDatetime = tEfHistoryEquipmentStatusLast.getStatusStartDatetime();
                    Duration duration = Duration.between( statusStartDatetime,now);
                    int secondsDifference = (int)duration.getSeconds();
                    update.setDurationSeconds(secondsDifference);
                    update.setDeviceId(tEfEquipmentDevice.getDeviceId());
                    update.setDataTime(now);
                    update.setStatusEndDatetime(now);
                    update.setId(tEfHistoryEquipmentStatusLast.getId());
                    String durationSecondsStr = GenericMethods.formatDuration(secondsDifference);
                    update.setDurationSecondsStr(durationSecondsStr);
                    iTEfHistoryEquipmentStatusService.updateTEfHistoryEquipmentStatus(update);
                }else {
                    Duration duration = Duration.between( tEfHistoryEquipmentStatusLast.getStatusStartDatetime(),now);
                    int secondsDifference = (int)duration.getSeconds();
                    update.setDurationSeconds(secondsDifference);
                    update.setDeviceId(tEfHistoryEquipmentStatusLast.getDeviceId());
                    update.setDataTime(now);
                    update.setStatusEndDatetime(now);
                    update.setId(tEfHistoryEquipmentStatusLast.getId());
                    String durationSecondsStr = GenericMethods.formatDuration(secondsDifference);
                    update.setDurationSecondsStr(durationSecondsStr);
                    int i = iTEfHistoryEquipmentStatusService.updateTEfHistoryEquipmentStatus(update);

                    tEfHistoryEquipmentStatus.setDeviceId(tEfEquipmentDevice.getDeviceId());
                    tEfHistoryEquipmentStatus.setEquipmentStatus(controllerStatus);
                    tEfHistoryEquipmentStatus.setDataTime(now);
                    tEfHistoryEquipmentStatus.setStatusStartDatetime(now);
                    tEfHistoryEquipmentStatus.setStatusEndDatetime(now.plusSeconds(1));
                    tEfHistoryEquipmentStatus.setDurationSeconds(1);
                    String durationSecondsStr2 = GenericMethods.formatDuration(1);
                    tEfHistoryEquipmentStatus.setDurationSecondsStr(durationSecondsStr2);
                    int i1 = iTEfHistoryEquipmentStatusService.insertTEfHistoryEquipmentStatus(tEfHistoryEquipmentStatus);
                }


            }

        }










        return tEfEquipmentDevice;
    }


/*

 */



}
